package com.yvan.leto;


import com.google.common.base.Strings;
import com.yvan.YvanUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;

import java.util.Map;

/**
 * Created by xiaoEight on 2018/6/14.
 */
@Slf4j
public class SpringBootListener implements ConfigListener, ApplicationContextInitializer<ConfigurableApplicationContext> {

    private final static String SPRING_BOOT_NAME = "applicationConfig:[leto-spring-root]";
    private String springBootPropertiesJson;
    private Map<String, Object> springBootMap;

    public SpringBootListener() {

    }

    @Override
    public String watchSegment() {
        return SegmentHelper.SPRING_BOOT;
    }

    @Override
    @SneakyThrows
    public void onChange(ConfigChangeEvent changeEvent) {
        final String yamlContent = changeEvent.getChanges();
        if (Strings.isNullOrEmpty(yamlContent)) {
            return;
        }
        springBootPropertiesJson = changeEvent.getChanges();
    }

    @Override
    @SuppressWarnings("unchecked")
    public void initialize(ConfigurableApplicationContext applicationContext) {
        final MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();

        if (Strings.isNullOrEmpty(springBootPropertiesJson)) {
            log.info("springboot configuration empty!");
            return;
        }
        final Map<String, Object> bootMap = (Map<String, Object>) YvanUtil.jsonToMap(springBootPropertiesJson);
        if (bootMap != null && !bootMap.isEmpty()) {
            propertySources.addFirst(new MapPropertySource(SPRING_BOOT_NAME, bootMap));
        }
        log.info("springboot configuration has inited!");
        springBootMap = bootMap;
    }

    @Override
    public void setup(LetoManage letoManage) {
        letoManage.springApplication.addInitializers(this);
    }

    public Map<String, Object> getSpringBootMap() {
        return springBootMap;
    }
}
